﻿using CsvHelper;
using CsvHelper.Configuration;
using CsvHelper.TypeConversion;
using System;
using System.Globalization;

namespace Yto.Common.CsvConverter
{
    public class DateTimeConverter : ITypeConverter
    {
        private string dateformat;

        public DateTimeConverter(string dtFormat)
        {
            dateformat = dtFormat;
        }
        public object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
        {
            if (!string.IsNullOrEmpty(text))
            {
                DateTime.TryParseExact(text, dateformat,
                    CultureInfo.InvariantCulture,
                    DateTimeStyles.None,
                    out DateTime dt);
                if (IsValidedSqlTime(dt))
                {
                    return dt;
                }
            }

            return null;
        }

        public string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
        {
            return ConvertToString(value, dateformat);
        }

        public string ConvertToString(object val, string format)
        {
            if (val == null)
            {
                return string.Empty;
            }

            if (DateTime.TryParse(val.ToString(), out DateTime dt))
            {
                return dt.ToString(format);
            }
            else
            {
                return string.Empty;
            }
        }

        public bool IsValidedSqlTime(DateTime? dt)
        {
            if (dt == null)
            {
                return true;
            }

            DateTime minValue = DateTime.Parse(System.Data.SqlTypes.SqlDateTime.MinValue.ToString());
            DateTime maxValue = DateTime.Parse(System.Data.SqlTypes.SqlDateTime.MaxValue.ToString());

            if (dt < minValue || dt > maxValue)
            {
                return false;
            }
            return true;
        }
    }
}
